package sk.octopuss.archery.utils;

import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.stereotype.Component;

import sk.octopuss.archery.annotation.RegexPattern;
import sk.octopuss.archery.dao.ItemDao;

@Component
public class RegexPatternConstraintValidator implements ConstraintValidator<RegexPattern, Object>, MessageSourceAware {

	private MessageSource messageSource;

	@Autowired
	ItemDao dao;
		
	private Pattern pattern;
	private String message;
	@Override
	public void initialize(final RegexPattern regexPattern) {
		// this.pattern=MessagesProvider.getMessage(regexPattern.source());
		try {
			message = messageSource.getMessage(regexPattern.source(), null, Locale.ROOT);
			this.pattern = Pattern.compile(message);
		} catch (final Exception e) {
			System.err.println("Key \"" + regexPattern.source() + "\" was not found in any reloadable bundle resource");
			e.printStackTrace();
		}
	}

	@Override
	public boolean isValid(final Object target, final ConstraintValidatorContext context) {
		final String fieldValue = (String) target;
		final Matcher matcher = pattern.matcher(fieldValue);
		if (matcher.find()) {
			return true;
		}

		//context.disableDefaultConstraintViolation();
		//context.buildConstraintViolationWithTemplate(this.message).addConstraintViolation();

		return false;
	}

	@Override
	public void setMessageSource(final MessageSource messageSource) {
		this.messageSource = messageSource;
	}

	
}
